require('dotenv').config();
const mysql = require('mysql2/promise');

// 数据库连接池
const pool = mysql.createPool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  user: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_DATABASE,
  ssl: {
    minVersion: 'TLSv1.2',
    rejectUnauthorized: true
  },
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 初始化数据库（如果不存在则创建表）
async function initializeDatabase() {
  try {
    const createTableQuery = `
      CREATE TABLE IF NOT EXISTS reviews (
        id INT AUTO_INCREMENT PRIMARY KEY,
        userId INT,
        userName VARCHAR(255),
        restaurantName VARCHAR(255),
        restaurantLocation VARCHAR(255),
        dishName VARCHAR(255),
        rating INT,
        reviewText TEXT,
        imageKeys TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )
    `;
    
    await pool.query(createTableQuery);
    console.log('数据库初始化成功');
  } catch (error) {
    console.error('数据库初始化失败:', error);
    throw error;
  }
}

// 导出连接池和初始化函数
module.exports = {
  pool,
  initializeDatabase
};
